package com.just.springjpa.dao;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.query.QueryUtils;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.List;
import java.util.Map;

@Repository
public class JPQLHandler {
    @PersistenceContext
    private EntityManager em;

    /**
     * JPQL dynamic query with page
     *
     * @param hqlString   a Java Persistence query string
     * @param params      key parameter map
     * @param pageable    org.springframework.data.domain.Pageable
     * @param resultClass the type of the query result
     * @return results with page
     * @since Java Persistence 2.0  Spring Boot 1
     */
    public <T> Page<T> query(String hqlString, Map<String, Object> params, Pageable pageable, Class<T> resultClass) {
        TypedQuery<T> query = em.createQuery(hqlString, resultClass);
        if (params != null) {
            for (String key : params.keySet()) {
                query.setParameter(key, params.get(key));
            }
        }
        if (pageable != null && pageable.getOffset() != 0) {
            query.setFirstResult(pageable.getOffset());
            query.setMaxResults(pageable.getPageSize());
        }
        //No fetch is allowed when counting
        hqlString = hqlString.replaceAll("join fetch", "join");
        TypedQuery<Long> cQuery = em.createQuery(QueryUtils.createCountQueryFor(hqlString), Long.class);
        return PageableExecutionUtils.getPage(query.getResultList(), pageable, cQuery::getSingleResult);
    }

    /**
     * JPQL dynamic query
     *
     * @param hqlString   a Java Persistence query string
     * @param params      key parameter map
     * @param resultClass the type of the query result
     * @return results
     * @since Java Persistence 2.0
     */
    public <T> List<T> query(String hqlString, Map<String, Object> params, Class<T> resultClass) {
        TypedQuery<T> query = em.createQuery(hqlString, resultClass);
        if (params != null) {
            for (String key : params.keySet()) {
                query.setParameter(key, params.get(key));
            }
        }
        return query.getResultList();
    }
}
